package l1j.server.server.templates;

import java.util.ArrayList;

import l1j.server.server.datatables.ItemTable;
import l1j.server.server.model.Instance.L1PcInstance;
import l1j.server.server.serverpackets.S_ServerMessage;
import l1j.server.server.serverpackets.S_SystemMessage;
import l1j.server.server.utils.Random;
import l1j.server.server.utils.collections.Lists;

public class ItemMaker {

	private int _boxType = 0;

	/**
	 * BOXTYPE: 預設0 為個別計算機率 設定為1時將類似寶箱共用一個機率
	 */
	public ItemMaker(int boxType) {
		_boxType = boxType;
	}

	private ArrayList<Material> _Materials = Lists.newArrayList();

	public void addMaterial(int itemId, int count) {
		_Materials.add(new Material(itemId, count));
	}

	private ArrayList<GetItem> _GetItems = Lists.newArrayList();

	public void addGetItem(int itemId, int count, int chance) {
		_GetItems.add(new GetItem(itemId, count, chance));
	}

	public boolean checkMaterials(L1PcInstance pc) {
		boolean result = true;
		for (Material m : _Materials) {
			if (!pc.getInventory().checkItemNotEquipped(m.m_itemId, m.m_count)) {
				result = false;
				String itemName = ItemTable.getInstance()
						.getTemplate(m.m_itemId).getName();
				pc.sendPackets(new S_SystemMessage(itemName + " 不足..."));
			}
		}
		return result;
	}

	public void consumeMaterials(L1PcInstance pc) {
		for (Material m : _Materials) {
			pc.getInventory().consumeItemNotEquip(m.m_itemId, m.m_count);
		}
	}

	public void getItem(L1PcInstance pc) {
		if (_boxType == 0) {
			for (GetItem g : _GetItems) {
				if (Random.chance(g.g_chance, 1000000)) {
					pc.getItem(g.g_itemId, g.g_count, 0, null);
				} else {
					pc.sendPackets(new S_ServerMessage(79));// 沒有任何事情發生
				}
			}
		} else {
			int totalChance = getTotalChance();
			for (GetItem g : _GetItems) {
				if (Random.chance(g.g_chance, totalChance)) {
					pc.getItem(g.g_itemId, g.g_count, 0, null);
					break;
				} else {
					totalChance -= g.g_chance;
				}
			}
		}
	}

	private int getTotalChance() {
		int total = 0;
		for (GetItem g : _GetItems) {
			total += g.g_chance;
		}
		return total;
	}

	private class Material {
		Material(int itemId, int count) {
			m_itemId = itemId;
			m_count = count;
		}

		int m_itemId;
		int m_count;
	}

	private class GetItem {
		GetItem(int itemId, int count, int chance) {
			g_itemId = itemId;
			g_count = count;
			g_chance = chance;
		}

		int g_itemId;
		int g_count;
		int g_chance;
	}
}
